import React, {Component} from "react";
import GridTable from '../../components/display/gridTable';
import {privateStubManager,prefixFile,privateTypeList} from "../../fetch/fetchApi";
import PropsType from "prop-types";
import { Button, Input , Row, Col, Select, Tooltip } from 'antd';
import locale from "antd/lib/date-picker/locale/zh_CN";
import {DatePicker, message} from "antd/lib/index";
import AreaPicker from '../../components/dataEntry/areaPicker';
import moment from 'moment';
const { RangePicker } = DatePicker;
const Option = Select.Option;

class PrivateStubManager extends Component {

    constructor (props) {
        super(props);
        this.props = props;
        this.state = {
            gridData: [],
            loadingmes: '查询',
            exportMes: '导出',
            loading: !1,
            joinRangeValue: [moment(this.currentTime(7), 'YYYY-MM-DD'),moment(this.currentTime(), 'YYYY-MM-DD')],
            chargeRangeValue: [moment(this.currentTime(7), 'YYYY-MM-DD'),moment(this.currentTime(), 'YYYY-MM-DD')],
            btnloading: !1,
            ajaxData: [],
            typeList: [],
            pagination: {
                total: 0
            }
        };
        this.init();
    }

    init () {
        this.query = {
            page: '1',
            pagecount: '10',
            startJoin: moment(this.currentTime(7), 'YYYY-MM-DD').format('YYYY-MM-DD').toString(),
            endJoin: moment(this.currentTime(), 'YYYY-MM-DD').format('YYYY-MM-DD').toString(),
            startTime: moment(this.currentTime(7), 'YYYY-MM-DD').format('YYYY-MM-DD').toString(),
            endTime: moment(this.currentTime(), 'YYYY-MM-DD').format('YYYY-MM-DD').toString()
        };
        // 初始化私桩类型
        this.findPrivateTypeList();
        // 设置表头
        this.tableColumns = [
            {
                title: '电桩编号',
                dataIndex: 'stubId',
                key: 'stubId',
                fixed: 'left'
            }, {
                title: '桩主账号',
                dataIndex: 'phone',
                key: 'phone',
                fixed: 'left'
            }, {
                title: '所属城市',
                dataIndex: 'proCity',
                key: 'proCity',
                className: 'column-nowrap'
            }, {
                title: '电桩地址',
                dataIndex: 'address',
                key: 'address',
                className: 'column-nowrap',
                render: (text, record) => (
                <Tooltip placement="topLeft" title={text} >
                    {text}
                </Tooltip>)
            }, {
                title: '加入时间',
                dataIndex: 'joinTime',
                key: 'joinTime',
                className: 'column-nowrap'
            }, {
                title: '私桩类型',
                dataIndex: 'stubTypeName',
                key: 'stubTypeName',
                className: 'column-nowrap'
            }, {
                title: '分享状态',
                dataIndex: 'shareStatus',
                key: 'shareStatus',
                className: 'column-nowrap'
            }, {
                title: '分享时间',
                dataIndex: 'shareTime',
                key: 'shareTime',
                className: 'column-nowrap'
            }, {
                title: '电费单价',
                dataIndex: 'feeRule',
                key: 'feeRule',
                className: 'column-nowrap',
                render: (text, record) => (
                <Tooltip placement="topLeft" title={text} >
                    {text}
                </Tooltip>)
            }, {
                title: '累计电量（度）',
                dataIndex: 'totalPower',
                key: 'totalPower',
                className: 'column-nowrap'
            }, {
                title: '自用电量（度）',
                dataIndex: 'selfPower',
                key: 'selfPower',
                className: 'column-nowrap'
            }, {
                title: '共享电量（度）',
                dataIndex: 'sharePower',
                key: 'sharePower',
                className: 'column-nowrap'
            }, {
                title: '白名单电量（度）',
                dataIndex: 'whitePower',
                key: 'whitePower',
                className: 'column-nowrap'
            }, {
                title: '平台服务费（元）',
                dataIndex: 'serviceFee',
                key: 'serviceFee',
                className: 'column-nowrap'
            }, {
                title: '状态',
                dataIndex: 'status',
                key: 'status',
                className: 'column-nowrap'
            }, {
                title: '销售代表',
                dataIndex: 'salesRepresentative',
                key: 'salesRepresentative',
                className: 'column-nowrap'
            }
        ];
    }

    // 获取系统时间
    currentTime (days) {
        let date = new Date();//获取当前时间
        if(days && days > 0){
            date.setDate(date.getDate() - days);
            return date;
        }
        return date;
    }

    // 提交查询
    queryChargeInfo () {
        this.query.page = '1';
        this.state.pagination.current = 1;
        this.setState({
            pagination: this.state.pagination
        });
        this.buildingApplyCb();
    }

    // 数据导出
    async exportData () {
        // 判断导出参数
        if (!this.query.startJoin && !this.query.startTime) {
            message.warn('请选择加入时间或充电时间', 1);
            return;
        }

        let excelUrl = prefixFile + '/privateStubExport.do?';
        let paramUrl = '';
        Object.keys(this.query).map( (key) => {
            paramUrl += key + '=' + this.query[key] + '&';
        });
        // 截取掉最后一个&符号
        if(paramUrl.length > 0){
            paramUrl = paramUrl.substr(0,paramUrl.length - 1)
        }

        window.location.href = excelUrl + paramUrl;
    }

    // 注入电桩编号
    pileCodeInputHandler (e) {
        this.query['stubId'] = e.target.value.toString();
    }

    // 注入桩主账号
    pilerAccountInputHandler (e) {
        this.query['phone'] = e.target.value.toString();
    }

    // 注入分享状态
    shareTypeInputHandler (e) {
        if (!isNaN(parseInt(e))){
            this.query['shareStatus'] = parseInt(e);
        }else{
            this.query['shareStatus'] = null;
        }
    }

    // 注入私桩类型
    szTypeInputHandler (e) {
        this.query['stubTypeId'] = e;
    }

    // 打开tab
    openTab (param, e) {
        this.props.onAdd.bind(window.LayoutTab)(e, param);
    }

    // 加入时间选择年份
    onJoinDataChange (e) {
        if (e[1]-e[0] > 7 * 24 * 60 * 6e4) {
            message.warn('选择范围请在7天内', 1);
            this.setState({
                'joinRangeValue': null
            });
            this.query['startJoin'] = '';
            this.query['endJoin'] = '';
            return;
        };
        this.setState({
            'joinRangeValue': e
        });
        this.query['startJoin'] = e[0] && e[0].format('YYYY-MM-DD').toString();
        this.query['endJoin'] = e[1] && e[1].format('YYYY-MM-DD').toString();
    }

    // 充电时间选择年份
    onChargeDataChange (e) {
        if (e[1]-e[0] > 7 * 24 * 60 * 6e4) {
            message.warn('选择范围请在7天内', 1);
            this.setState({
                'chargeRangeValue': null
            });
            this.query['startTime'] = '';
            this.query['endTime'] = '';
            return;
        };
        this.setState({
            'chargeRangeValue': e
        });
        this.query['startTime'] = e[0] && e[0].format('YYYY-MM-DD').toString();
        this.query['endTime'] = e[1] && e[1].format('YYYY-MM-DD').toString();
    }

    // fetch DataSource
    async findPrivateStubList () {
        this.setState({
            loading: !0,
            btnloading: !0
        });
        try {
            const resData = await privateStubManager(this.query);
            if (resData.data.code === '200') {
                const pagination = {
                    total: resData.data.pageLimit.totalCount,
                    onShowSizeChange: (current) => {
                        this.turnPage(current)
                    },
                    onChange:(current) => {
                        this.turnPage(current)
                    }
                }
                this.setState({
                    pagination
                });
                return resData.data.data;
            }
        } catch (e) {
            console.log(e);
        }
    }

    // 私桩类型列表获取
    async findPrivateTypeList (){
        try {
            const resData = await privateTypeList();
            if (resData.data.code === '200') {
                if(resData.data.data){
                    console.log(this);
                    this.setState({
                        typeList: [
                            <Select placeholder="私桩类型" onChange={this.szTypeInputHandler.bind(this)}>
                                <Option value='' key=''>全部</Option>
                            {
                                resData.data.data.map( (item) => {
                                    console.log(item);
                                    return <Option value={item.stubTypeId} key={item.stubTypeId}>{item.stubTypeName}</Option>
                                })
                            }
                            </Select>
                            ]
                    })
                }
            }
        } catch (e) {
            console.log(e);
        }
    }

    // 跳转页码
    turnPage (current) {
        this.query['page'] = current.toString();
        this.buildingApplyCb();
    }

    buildingApplyCb () {
        this.findPrivateStubList().then((data) => {
            this.setState({
                loading: !1,
                btnloading: !1,
                gridData: data
            });
         });
    }

    // 获取选择的地址编码
  onPickArea (val) {
      if(val.length){
          this.query['areaCode'] = val[1] + '00';
      }else{
          this.query['areaCode'] = '';
      }
  }

    render (){
        const Content = <div className="sc-page-content">
            <div className="page-toolbar">
                <Row gutter={8}>
                    <Col lg={2} xl={2}>
                        <label>加入时间</label>
                    </Col>
                    <Col lg={6} xl={6}>
                        <RangePicker value={this.state.joinRangeValue}
                                     onChange={this.onJoinDataChange.bind(this)} locale={locale} format="YYYY-MM-DD"/>
                    </Col>
                    <Col lg={2} xl={2}>
                        <label>充电时间</label>
                    </Col>
                    <Col lg={6} xl={6}>
                        <RangePicker value={this.state.chargeRangeValue}
                                     onChange={this.onChargeDataChange.bind(this)} locale={locale} format="YYYY-MM-DD"/>
                    </Col>
                    <Col lg={4} xl={4}>
                        <Input placeholder="桩主账号精确查询" onChange={this.pilerAccountInputHandler.bind(this)}/>
                    </Col>
                    <Col lg={4} xl={4}>
                        <Input placeholder="电桩编号精确查询" onChange={this.pileCodeInputHandler.bind(this)}/>
                    </Col>
                </Row>
                <Row gutter={8}>
                    <Col lg={4} xl={4} className="whole-fill">
                        <Select placeholder="分享状态" onChange={this.shareTypeInputHandler.bind(this)}>
                            <Option value="">全部</Option>
                            <Option value="0">未分享</Option>
                            <Option value="1">已分享</Option>
                        </Select>
                    </Col>
                    <Col lg={4} xl={4} className="whole-fill">
                        {this.state.typeList}
                    </Col>
                    <Col lg={2} xl={2}>
                        <label>所属城市</label>
                    </Col>
                    <Col lg={6} xl={6}>
                      <AreaPicker pickAreaHandler={this.onPickArea.bind(this)}/>
                    </Col>
                    <div  className="button-inlineBlock">
                        <Button type="primary" onClick={this.queryChargeInfo.bind(this)}>{this.state.loadingmes}</Button>
                    </div>
                    <div  className="button-inlineBlock">
                        <Button type="primary" icon="download" onClick={this.exportData.bind(this)}>{this.state.exportMes}</Button>
                    </div>
                </Row>
            </div>
            <div className="page-panel">
                <GridTable postyle="table-center" data={this.state.gridData} columns={this.tableColumns} loading={this.state.loading} pagination={this.state.pagination}/>
            </div>
        </div>;

        return Content;
    }

}

export default PrivateStubManager;

PrivateStubManager.propTypes = {
    onAdd: PropsType.func
}